// pages/registration/visitor.js
var Constant = require('../../utils/constant.js');
const app = getApp()
var personId = "";
var personKey = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '获取验证码', //倒计时 
    currentTime: 30,
    disabled: false,
    userName: '业主访客',
    phoneNum: '',
    startTime: '',
    endTime: '',
    timeList: ['一天','两天'], 
    time: '一天',
    takePicType: 'visitor',
    photoPath: '/images/img_add.png',
    imageSelect: false,
    picBase64: '',
    picId: '',

    localName: "请选择",
    localLists:[],
    localvalue:'',
    

    multiArray: [],
    year: "",
    month: "",
    day: "",
    startHour: "",
    endHour: "",
    orderData: "选择开始时间",
    deadLine: "选择截止时间",
    index: 0,
    multiIndex: [0, 0, 0, 0, 0, 0],
    orderTimeStamp: '',
    deadLineTimeStamp: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var date = new Date();
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()


    var surplusMonth = this.surplusMonth(year);
    console.log(surplusMonth)
    var surplusDay = this.surplusDay(year, month, day);
    console.log(surplusDay)
    var surplusHour = this.surplusHour(year, month, day, hour)
    console.log(surplusHour)

    this.setData({
      multiArray: [[year + '年', (year + 1) + '年', (year + 2) + '年'],
        surplusMonth,
        surplusDay,
      surplusHour[0],
      // ['~'],
      // surplusHour[1]
      ],
      year: year,
      month: month,
      day: day,
      startHour: surplusHour[0][0],
      endHour: surplusHour[1][0],
    })

    let dateStr =
      this.data.multiArray[0][this.data.multiIndex[0]] +
      this.data.multiArray[1][this.data.multiIndex[1]] +
      this.data.multiArray[2][this.data.multiIndex[2]] +
      this.data.multiArray[3][this.data.multiIndex[3]];

    let nextDay = this.data.multiArray[2][this.data.multiIndex[2]];
    let nextNum = parseInt(nextDay.substring(0, nextDay.length - 1)) + 1;
    let nextStr = nextNum + "日";
    let dateNext =
      this.data.multiArray[0][this.data.multiIndex[0]] +
      this.data.multiArray[1][this.data.multiIndex[1]] +
      nextStr +
      this.data.multiArray[3][this.data.multiIndex[3]];


    let year1 = this.data.multiArray[0][this.data.multiIndex[0]];
    let month1 = this.data.multiArray[1][this.data.multiIndex[1]];
    let day1 = this.data.multiArray[2][this.data.multiIndex[2]];
    let hours1 = this.data.multiArray[3][this.data.multiIndex[3]];
    this.data.orderTimeStamp = getTimeStamp(year1, month1, day1, hours1);
    this.data.deadLineTimeStamp = getTimeStamp(year1, month1, nextStr, hours1);

    this.setData({
      orderData: dateStr,
      deadLine: dateNext,
      // localName: app.globalData.userLocalList[0],
      localLists: app.globalData.userLocalList
    })


    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.photoPath != "/images/img_add.png") {
      if (that.data.picId == "") {
        that.setData({
          photoPath: currPage.data.photoPath,
          imageSelect: currPage.data.imageSelect,
        });
        picToBase64(that.data.photoPath, this)
      } else {
        //如果是从服务器相册里面选图
        var url = Constant.BASEURL + "/" + currPage.data.photoPath;
        console.log(url)
        that.setData({
          picBase64: currPage.data.photoPath,
          photoPath: url,
          imageSelect: currPage.data.imageSelect,
          picId: currPage.data.picId,
        });
      }
    }


    var that = this;
    wx.showLoading({
      title: '请稍后',
    })
    wx.request({
      url: Constant.BASEURL + Constant.GET_SHARE_ID,
      method: 'GET',
      success(res) {
        console.log(res.data)
        personId = res.data.id;
        personKey = res.data.key;
        wx.hideLoading();
      },
      fail(res) {
        console.log("系统错误")
        wx.hideLoading();
        wx.showToast({
          title: '请检查网络',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  
  onShareAppMessage: function () {
    var timestamp = Date.parse(new Date());
    var that = this;
   
    return {
      title: '分享给访客注册',
      path: 'pages/registration/sharetovisitor?openid=' + app.globalData.openid + "&userType=visitor" + "&location=" + app.globalData.unitno + "&timestamp=" + timestamp + "&personId=" + personId + "&personKey=" + personKey + "&startTime=" + that.data.orderTimeStamp + "&endTime=" + that.data.deadLineTimeStamp + "&localLists=" + app.globalData.userLocalList + "&userOrgCodelList=" + app.globalData.userOrgCodelList,
      imageUrl: "",
      success(e) {
        wx.showShareMenu({
          withShareTicket: true
        });
        
      },
      faild(e) {
        console.log(e)
      }
    }
    
  },

  phoneNum: function (e) {
    this.setData({
      phoneNum: e.detail.value
    })
  },
  userName: function (e){
    this.setData({
      userName: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    this.setData({
      time: this.data.timeList[e.detail.value],
    })

  },
  getCode: function (options) {
    var that = this;
    var currentTime = that.data.currentTime;
    var interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime + '秒'
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '获取验证码',
          currentTime: 30,
          disabled: false
        })
      }
    }, 1000)
  },
  getVerificationCode() {

    var phone = this.data.phoneNum;
    var that = this;
    if (phone.length != 11) {
      console.log(phone.length)
    }

    wx.request({
      url: 'https://192.168.0.121/faceAuditinglistController.do?getRancode&personphone=' + phone,
      method: 'GET',
      success: function (res) {
        console.log(res.data)
        that.getCode();
        that.setData({
          disabled: true
        })
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function () {
      }
    })


  },

  bindCommunityChange: function(e){
    this.setData({
      localName: this.data.localLists[e.detail.value],
      localvalue: e.detail.value
    })
  },

  takePicture: function(e){
    var that = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择", "从历史记录中选择"],
      success: function(res){
        console.log(res.tapIndex)
        if(res.tapIndex == 0){
          wx.navigateTo({
            url: '../takephoto/takephoto?takePicType=' + that.data.takePicType
          })
        } else if(res.tapIndex == 1){
          wx.chooseImage({
            count: 1,
            sourceType: ['album'],
            sizeType: 'compressed',
            success: function(res) {
              var picPath = res.tempFilePaths[0];
              console.log(picPath);
              setTimeout(function () {
              wx.showLoading({
                title: '检测中',
              })
              },200);
              let manager = wx.getFileSystemManager();
              manager.readFile({
                filePath: picPath,
                encoding: 'base64',
                success: function (res) {
                  //console.log(res.data)
                  that.data.picBase64 = res.data;
                  wx.request({
                    url: Constant.BASEURL + Constant.PICDETECT_URL,
                    method: 'POST',
                    data: { "personphoto": that.data.picBase64 },
                    success: function (res) {
                      console.log(res.data)
                      var retCode = res.data.obj;
                      if (retCode == "0") {
                        that.setData({
                          photoPath: picPath,
                          imageSelect: true,
                        });
                        wx.hideLoading();
                      } else {
                        let state_msg = "";
                        if (retCode == Constant.STATE_ERROR_FILE_TYPE) {
                          state_msg = '网络请求错误';
                        } else if (retCode == Constant.STATE_ERROR_FILE_INCOMPLETE) {
                          state_msg = '发送的数据不完整，请检查网络连接';
                        } else if (retCode == Constant.STATE_ERROR_FILE_DATA) {
                          state_msg = '不能解析图像数据';
                        } else if (retCode == Constant.STATE_ERROR_FACE_NUM) {
                          state_msg = '人脸数量不正确，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_YIN_YANG) {
                          state_msg = '光线不均匀，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_BORDER) {
                          state_msg = '请将人脸放在画面中央';
                        } else if (retCode == Constant.STATE_ERROR_FACE_RESOLUTION) {
                          state_msg = '人脸太小，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_ANGLE) {
                          state_msg = '人脸角度偏差太大，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_IMAGE_QUALITY) {
                          state_msg = '图像质量太差';
                        } else {
                          state_msg = '未知错误，错误码' + retCode;
                        }
                        wx.hideLoading();
                        wx.showModal({
                          title: '提示',
                          content: state_msg,
                          showCancel: false,
                          success: function (res) { },
                        })
                      }
                      // wx.hideLoading();
                    },
                    fail: function (res) {
                      wx.hideLoading();
                      wx.showToast({
                        title: '请检测网络连接',
                        icon: 'none'
                      })
                    }
                  })
                },
                fail: function (res) {
                  console.log(res)
                  wx.showModal({
                    title: '提示',
                    content: '照片无效，请重新选择',
                    showCancel: false,
                    success: function (res) { },
                  })
                }
              })
              
              
            },
          })
        } else {
          wx.navigateTo({
            url: '../takephoto/visitorpicture?isRegister='+true,
          })
        }
      }
    })
    
    
  },
  
  buttonNext: function(e){
    
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var n = timestamp * 1000;
    var date = new Date(n);
    //年
    var Y = date.getFullYear();
    //月
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    //时
    var h = date.getHours();
    //分
    var m = date.getMinutes();
    //秒
    var s = date.getSeconds();
    console.log("当前时间：" + Y + M + D + h + ":" + m + ":" + s);
    console.log("当前时间戳为：" + timestamp);  //加一天 24 * 60 * 60
    var that = this;
    
    if (that.data.deadLineTimeStamp <= that.data.orderTimeStamp || that.data.deadLineTimeStamp == '' || that.data.orderTimeStamp == ''){
      wx.showToast({
        title: '时间选择不正确',
        icon: 'none',
      })
      return ;
    }

    if (this.data.localName == '') {
      wx.showToast({
        title: '请选择小区',
        icon: 'none',
      })
      return;
    }
    
    if (that.data.photoPath == "/images/img_add.png"){
      wx.showToast({
        title: '需要上传照片',
        icon: 'none',
      })
      return;
    }
    
    var muuid = uuid(16, 9);
    console.log("生成的uuid" + muuid);
    //that.data.endTime = n + 24 * 60 * 60 * t * 1000;
    wx.showLoading({
      title: '请稍后',
    })
    wx.request({
      url: Constant.BASEURL + Constant.USER_VISITOR_URL,
      method: 'POST',
      data: {
        "id": that.data.picId, "personname": that.data.userName, "persontype": "98", "openid": app.globalData.openid, "personphoto": that.data.picBase64, "estarttime": that.data.orderTimeStamp, "eendtime": that.data.deadLineTimeStamp, "unitno": app.globalData.userOrgCodelList[this.data.localvalue]
          },
      success: function(res){
        console.log(res.data)
        if(res.data.respCode == "0"){
          wx.showModal({
            title: '恭喜',
            content: '添加访客成功!',
            showCancel: false,
            success: function(){
              wx.navigateBack({
                delta: 2
              });
            }
          })
          
        }else{
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
        wx.hideLoading();
      },
      fail: function(res){
        wx.hideLoading();
        wx.showToast({
          title: '请求失败,请检查网络',
          icon: 'none',
        })
        console.log('请求失败')
      }
    })
  },






  //月份计算
  surplusMonth: function (year) {
    var date = new Date();
    var year2 = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    var monthDatas = [];
    if (year == year2) {
      var surplusMonth = 12 - month;
      monthDatas.push(month + "月")
      for (var i = month; i < 12; i++) {
        monthDatas.push(i + 1 + "月")
      }
    } else {
      for (var i = 0; i < 12; i++) {
        monthDatas.push(i + 1 + "月")
      }
    }

    return monthDatas;
  },
  //天数计算
  surplusDay: function (year, month, day) {
    var days = 31;
    var dayDatas = [];
    var date = new Date();
    var year2 = date.getFullYear()
    var month2 = date.getMonth() + 1

    switch (parseInt(month)) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        days = 31;

        break;
      //对于2月份需要判断是否为闰年
      case 2:
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
          days = 29;

          break;
        } else {
          days = 28;

          break;
        }

      case 4:
      case 6:
      case 9:
      case 11:
        days = 30;

        break;

    }
    if (year == year2 && month == month2) {
      dayDatas.push(day + "日")
      for (var i = day; i < days; i++) {
        dayDatas.push(i + 1 + "日")
      }
    } else {
      console.log(month + "月" + days + "天")
      for (var i = 0; i < days; i++) {
        dayDatas.push(i + 1 + "日")
      }
    }
    return dayDatas;
  },
  //时间计算
  surplusHour: function (year, month, day, hour) {
    var date = new Date();
    var year2 = date.getFullYear()
    var month2 = date.getMonth() + 1
    var day2 = date.getDate();
    var hourEnd = [1,2,3,4,5,6,7, 8,9,10,11, 12,13,14,15, 16,17,18,19, 20,21,22,23, 24];
    var hours = [['00时', '01时', '02时', '03时', '04时', '05时', '06时', '07时', '08时', '09时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时',], ['04时', '08时', '12时', '16时', '20时', '24时']];

    if (year == year2 && month == month2 && day == day2) {
      var hour2 = hour
      var j = 0;
      for (var i = 0; i < hourEnd.length; i++) {
        console.log("离24点还" + (hourEnd[i] - hour))
        if ((hourEnd[i] - hour) > 0) {
          console.log("i" + i)
          j = i;
          break;
        }
      }
      var surplusHours = [[], []];
      for (var i = j; i < hours[0].length; i++) {
        console.log(hours[0][i])
        surplusHours[0].push(hours[0][i]);
      }
      for (var i = j; i < hours[1].length; i++) {
        console.log(hours[1][i])
        surplusHours[1].push(hours[1][i]);
      }

      hours = surplusHours;
    }
    return hours;
  },
  //某一列的值改变时触发
  bindMultiPickerColumnChange: function (e) {
    var date = new Date();
    var year1 = date.getFullYear()
    var month1 = date.getMonth() + 1
    var day1 = date.getDate()
    var hour1 = date.getHours()
    console.log("当前年份" + this.data.month + '修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex,
      year: this.data.year,
      month: this.data.month,
      day: this.data.day,
      startHour: this.data.startHour,
      endHour: this.data.startHour,
    };
   
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        var yearStr = data.multiArray[e.detail.column][e.detail.value];
        var year = yearStr.substring(0, yearStr.length - 1)
        data.year = parseInt(year);
        var surplusMonth = this.surplusMonth(year);
        data.multiArray[1] = surplusMonth;

        if (data.year == year1) {
          data.month = month1;
        } else {
          data.month = 1;
        }
        if (data.year == year1 && month1 == data.month) {
          data.day = day1;
        } else {
          data.day = 1;
        }

        var surplusDay = this.surplusDay(data.year, data.month, data.day);

        data.multiArray[2] = surplusDay;
        var surplusHour;
        if (data.year == year1 && month1 == data.month && data.day == day1) {
          surplusHour = this.surplusHour(data.year, data.month, data.day, hour1)
        } else {
          surplusHour = this.surplusHour(data.year, data.month, data.day, 1)
        }

        console.log(surplusHour)

        data.multiArray[3] = surplusHour[0];
        //data.multiArray[5] = surplusHour[1];


        data.startHour = surplusHour[0];
        data.endHour = surplusHour[1];

        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        data.multiIndex[3] = 0;
        //data.multiIndex[5] = 0;
        break;
      case 1:
        console.log('选择月份' + data.multiArray[e.detail.column][e.detail.value]);

        var monthStr = data.multiArray[e.detail.column][e.detail.value];
        var month = monthStr.substring(0, monthStr.length - 1);

        data.month = month;
        data.day = 1;

        if (data.year == year1 && month1 == data.month) {
          data.day = day1;
        } else {
          data.day = 1;
        }

        var surplusDay = this.surplusDay(data.year, data.month, data.day);

        data.multiArray[2] = surplusDay;

        var surplusHour;
        if (data.year == year1 && month1 == data.month && data.day == day1) {
          surplusHour = this.surplusHour(data.year, data.month, data.day, hour1)
        } else {
          surplusHour = this.surplusHour(data.year, data.month, data.day, 1)
        }


        data.multiArray[3] = surplusHour[0];
        //data.multiArray[5] = surplusHour[1];


        data.startHour = surplusHour[0];
        data.endHour = surplusHour[1];
        data.multiIndex[2] = 0;
        data.multiIndex[3] = 0;
        //data.multiIndex[5] = 0;
        break;
      case 2:
        console.log('选择日' + data.multiArray[e.detail.column][e.detail.value]);
        var dayStr = data.multiArray[e.detail.column][e.detail.value];
        var day = dayStr.substring(0, dayStr.length - 1);
        data.day = day;

        var surplusHour;
        if (data.year == year1 && month1 == data.month && data.day == day1) {
          surplusHour = this.surplusHour(data.year, data.month, data.day, hour1)
        } else {
          surplusHour = this.surplusHour(data.year, data.month, data.day, 1)
        }


        data.multiArray[3] = surplusHour[0];
        //data.multiArray[5] = surplusHour[1];



        data.startHour = surplusHour[0];
        data.endHour = surplusHour[1];

        data.multiIndex[3] = 0;
        //data.multiIndex[5] = 0;
        break;
      case 3:
        console.log('起始时间' + data.multiArray[e.detail.column][e.detail.value]);

        var hourStr = data.multiArray[e.detail.column][e.detail.value];
        var hour = hourStr.substring(0, hourStr.length - 1);
        data.startHour = hour;
        console.log('起始时间' + hour);
        var endhours2 = [];
        if (data.year == year1 && data.month == month1 && data.day == day1) {
          var surplusHour = this.surplusHour(data.year, data.month, data.day, hour);
          endhours2 = surplusHour[1]
        } else {
          var end = ['04时', '08时', '12时', '16时', '20时', '24时'];
          for (var i = e.detail.value; i < end.length; i++) {
            endhours2.push(end[i]);
          }
        }


        //data.multiArray[5] = endhours2;
        //data.multiIndex[5] = 0;

        break;
      case 5:
        var hourStr = data.multiArray[e.detail.column][e.detail.value];
        var hour = hourStr.substring(0, hourStr.length - 1);
        data.endHour = hour;
        console.log('结束时间' + data.multiArray[e.detail.column][e.detail.value]);
        break;
    }
    this.setData(data)

  },
  //value 改变时触发 change 事件
  bindMultiPickerChange: function (e) {
    // var dateStr =
    //   this.data.multiArray[0][this.data.multiIndex[0]] +
    //   this.data.multiArray[1][this.data.multiIndex[1]] +
    //   this.data.multiArray[2][this.data.multiIndex[2]] +
    //   this.data.multiArray[3][this.data.multiIndex[3]] +
    //   this.data.multiArray[4][this.data.multiIndex[4]] +
    //   this.data.multiArray[5][this.data.multiIndex[5]];

    var dateStr =
      this.data.multiArray[0][this.data.multiIndex[0]] +
      this.data.multiArray[1][this.data.multiIndex[1]] +
      this.data.multiArray[2][this.data.multiIndex[2]] +
      this.data.multiArray[3][this.data.multiIndex[3]];

    let year = this.data.multiArray[0][this.data.multiIndex[0]];
    let month = this.data.multiArray[1][this.data.multiIndex[1]];
    let day = this.data.multiArray[2][this.data.multiIndex[2]];
    let hours = this.data.multiArray[3][this.data.multiIndex[3]];
    this.data.orderTimeStamp = getTimeStamp(year, month, day, hours);
    console.log('picker发送选择改变，日期为： 年', year,"月：",month,"日：",day,"小时：",hours)
    console.log('picker发送选择改变，携带值为', dateStr)
    this.setData({
      orderData: dateStr
    })
  },

  binddeadLineMultiPickerChange: function (e) {
    var dateStr =
      this.data.multiArray[0][this.data.multiIndex[0]] +
      this.data.multiArray[1][this.data.multiIndex[1]] +
      this.data.multiArray[2][this.data.multiIndex[2]] +
      this.data.multiArray[3][this.data.multiIndex[3]];

    let year = this.data.multiArray[0][this.data.multiIndex[0]];
    let month = this.data.multiArray[1][this.data.multiIndex[1]];
    let day = this.data.multiArray[2][this.data.multiIndex[2]];
    let hours = this.data.multiArray[3][this.data.multiIndex[3]];
    this.data.deadLineTimeStamp = getTimeStamp(year, month, day, hours);
    console.log('picker发送选择改变，携带值为', dateStr)
    this.setData({
      deadLine: dateStr
    })
  },

})

function picToBase64(path, that) {
  let manager = wx.getFileSystemManager();
  manager.readFile({
    filePath: path,
    encoding: 'base64',
    success: function (res) {
      console.log("编码base64成功")
      that.data.picBase64 = res.data;
    },
    fail: function (res) {
      console.log(res)
    }
    })
  }


function uuid(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [], i;
  radix = radix || chars.length;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

function getTimeStamp(year,month,day,hours){
  var time = year.substring(0, year.length - 1) + "-" + month.substring(0, month.length - 1) + "-" + day.substring(0, day.length - 1) + " " + hours.substring(0, hours.length - 1) + ":00:00";
  var date = new Date(time); 
  var time1 = date.getTime();
  console.log("转换之前", time, "转换成的时间戳：", time1);
  return time1;
}